<? defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller_Template {

    public $errors = array();

    public function before()
    {
        parent::before();

        if (isset($_FILES['picture'])){
            $validate = Validation::factory($_FILES);

            // Добавление правил валидации значения 'picture'
            $validate->rule('picture', 'Upload::valid')
                ->rule('picture', 'Upload::image')
                ->rule('picture', 'Upload::type', array(':value', array('jpg', 'jpeg', 'png')));

            if ($validate->check())
            {
                $path = 'upload';
                $extension = strtolower(pathinfo($_FILES['picture']['name'], PATHINFO_EXTENSION));
                $file = uniqid().'.'.$extension;
                $filename = Upload::save($_FILES['picture'], $file, $path, 0777);
                $img = Image::factory($filename);

                if ($img->height > 200 or $img->width > 150){
                    $c = ($img->width/$img->height > 0.75)?Image::HEIGHT:Image::WIDTH;
                    $img = $img->resize(150, 200, $c);
                    $img->crop(150, 200, 0, 0);
                }

                $img->save($path.'/thumb_'.$file);
                $image = ORM::factory('file');
                $image->file = $path.'/'.$file;
                $image->thumb = $path.'/thumb_'.$file;
                if ($this->request->post('description'))
                $image->description = $this->request->post('description');
                $image->status = 1;
                $image->user_id = 1;
                $image->uploaded = time();
                $image->save();
            }
            else
            {
                $this->errors = array_merge($this->errors, $validate->errors('upload'));
            }
        }

        if ($this->auto_render)
        {
            $this->template->content = 'Content not set!';


            $this->template->styles = array();
            $this->template->scripts = array();

        }
    }

    public function action_index()
    {

    }

    public function after()
    {
        if ($this->auto_render)
        {
            $styles = array(
                URL::site('assets/css/style.css') => 'screen',
                URL::site('assets/jquery.fancybox.css') => 'screen',
            );

            $scripts = array(
                URL::site('assets/js/jquery-1.9.0.js'),
                URL::site('assets/jquery.fancybox.js'),
                URL::site('assets/js/core.js'),
            );

            $this->template->styles = array_merge($styles, $this->template->styles);
            $this->template->scripts = array_merge($scripts, $this->template->scripts);
            $this->template->errors = $this->errors;
        }
        parent::after();
    }

} // End Welcome
